<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      <el-breadcrumb-item>用户详情</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input placeholder="请输入内容" v-model="paramsInfo.query" clearable @clear="handleCurrentChange(1)">
            <el-button slot="append" icon="el-icon-search" @click="handleCurrentChange(1)"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        border
        :data="userList"
        style="width: 100%">
        <el-table-column
          type="index">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          width="180"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          width="180"
          label="角色">
        </el-table-column>
        <el-table-column
          width="180"
          label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" v-on:change="stateChange(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column
          width="180"
          label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editUserInfo(scope.row)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="open(scope.row)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="paramsInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      center
      @close="onDialogClose">
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"/>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog
      title="修改用户"
      :visible.sync="edtDialogVisible"
      width="50%"
      center
      @close="onEdtDialogClose">
      <el-form :model="edtFormInfo" :rules="rules" ref="edtFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="edtFormInfo.username" disabled/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="edtFormInfo.email"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="edtFormInfo.mobile"/>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="edtDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirmEditInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data () {
    var checkEmail = (rule, value, callback) => {
      const emailCheck = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (emailCheck.test(value)) {
        callback()
      } else {
        callback(new Error('请输入合法的邮箱'))
      }
    }
    var checkMobil = (rule, value, callback) => {
      const mobilCheck = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (mobilCheck.test(value)) {
        callback()
      } else {
        callback(new Error('请输入合法的手机号'))
      }
    }
    return {
      userList: [],
      paramsInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      addDialogVisible: false,
      // 添加弹窗表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 6,
            message: '用户名3到6个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '用户名3到6个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobil,
            trigger: 'blur'
          }
        ]
      },
      edtDialogVisible: false,
      edtFormInfo: {}
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.paramsInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.total = res.data.total
        this.userList = res.data.users
      }
    },
    // 改变每页多少条时触发
    handleSizeChange: function (size) {
      this.paramsInfo.pagesize = size
      this.paramsInfo.pagenum = 1
      this.getUserList()
    },
    // 改变当前页时触发
    handleCurrentChange: function (page) {
      this.paramsInfo.pagenum = page
      this.getUserList()
    },
    stateChange:
      async function (info) {
        console.log(info)
        const { data: res } = await this.$http.put(`users/${info.id}/state/${info.mg_state}`)
        if (res.meta.status !== 200) {
          info.mg_state = !info.mg_state
          this.$message.error('保存失败')
        } else {
          this.$message.success('保存成功')
        }
      },
    onDialogClose: function () {
      this.$refs.addFormRef.resetFields()
    },
    addUser: function () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', this.addForm)
          console.log(res)
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
          } else {
            this.addDialogVisible = false
            this.$message.success('添加成功')
            this.paramsInfo.pagenum = 1
            await this.getUserList()
          }
        } else {
          this.$message.error('请填写完整信息')
        }
      })
    },
    editUserInfo: function (info) {
      this.edtDialogVisible = true
      this.edtFormInfo = info
    },
    onEdtDialogClose: function () {
      this.$refs.edtFormRef.resetFields()
    },
    confirmEditInfo: function () {
      this.$refs.edtFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put('users/' + this.edtFormInfo.id, this.edtFormInfo)
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          } else {
            this.edtDialogVisible = false
            this.$message.success('修改成功')
            await this.getUserList()
          }
        } else {
          this.$message.error('请填入合法信息')
        }
      })
    },

    open: function (info) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + info.id)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        } else {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          await this.getUserList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang="less">

.el-card {
  margin-top: 20px;
  /*box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15)*/
  /*h-shadow水平阴影的位置;v-shadow 垂直阴影的位置;blur 模糊距离; color 阴影的颜色;*/
  /*!important 提升指定样式规则的应用优先权。*/
  box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-table {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 13px;
}

</style>
